package com.hsytech.dijiebao.utils;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FileUtil {
	/**
	 * 鑾峰�? raw, drawable 绛夋枃浠跺す涓殑鏂囦欢鐨勮緭鍏ユ祦
	 * 
	 * @param context
	 *            涓婁笅鏂�?
	 * @param rawResId
	 *            R.raw.certain_db, R.drawable.ic_launcher
	 * @return 鏂囦欢鐨勮緭鍏ユ�?
	 */
	public static InputStream getInputStream(Context context, int rawResId) {
		InputStream is = context.getResources().openRawResource(rawResId);
		return is;
	}

	/**
	 * 鑾峰�? assets 鏂囦欢澶逛腑鐨勬枃浠剁殑杈撳叆娴�?
	 * 
	 * @param context
	 *            涓婁笅鏂�?
	 * @param assetsPath
	 *            "db/certain_db.sqlite"
	 * @return 鏂囦欢鐨勮緭鍏ユ�?
	 * @throws IOException
	 */
	public static InputStream getInputStream(Context context, String assetsPath) throws IOException {
		InputStream is = context.getResources().getAssets().open(assetsPath);
		return is;
	}

	/**
	 * 鍩虹鏂囦欢澶� <br />
	 * 瀛樺湪澶栫疆瀛樺偍鍗�?: /SdCard/Soft2T/com.soft2t.imk2tbaseframework/<br />
	 * 鎴栬��<br />
	 * 娌℃湁澶栫疆瀛樺偍鍗�?: /data/data/com.soft2t.imk2tbaseframework/files/<br />
	 * 
	 * @return 淇濆瓨鏂囦欢鐨勮矾寰勫墠缂�
	 */
	public static String getBaseSavePath(Context context) {
		String baseSavePath;

		if (isSDCardEnable()) {
			baseSavePath = getSDCardPath_M1();
		} else {
			baseSavePath = context.getFilesDir().getAbsolutePath();
		}

		return baseSavePath;
	}

	/**
	 * 鍒ゆ柇SDCard鏄惁鍙敤
	 * 
	 * @return
	 */
	public static boolean isSDCardEnable() {
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}

	/**
	 * 鑾峰彇绯荤粺(鍐呴�?)瀛樺偍璺緞
	 * 
	 * @return
	 */
	public static String getRootDirectoryPath() {
		return Environment.getRootDirectory().getAbsolutePath();
	}

	/**
	 * 鑾峰彇鍐呯疆SD鍗�(sdcrad0)璺�?
	 * 
	 * @return
	 */
	public static String getSDCardPath_M1() {
		return Environment.getExternalStorageDirectory().getAbsolutePath();
	}

	/**
	 * 鑾峰彇鍐呯疆SD鍗�(sdcrad0)璺�?
	 * 
	 * @return
	 */
	@Deprecated
	public static String getSDCardPath_M2() {
		final String[] pathArray = new String[] { "/storage/sdcard0", "/mnt/sdcard0", "/mnt/sdcard" };

		// String sdCard_1 = recursion_M1(pathArray, 0);

		String sdCard_1 = recursion_M2(pathArray);

		return sdCard_1;
	}

	/**
	 * 鑾峰彇澶栫疆SD鍗�(sdcrad1)璺�?
	 * 
	 * @return
	 */
	public static String getSDCard2Path_M1() {
		String sdcard_path = null;
		String sd_default = Environment.getExternalStorageDirectory().getAbsolutePath();
		// Log.d("text", sd_default);

		if (sd_default.endsWith("/")) {
			sd_default = sd_default.substring(0, sd_default.length() - 1);
		}

		// 寰楀埌璺緞
		try {
			Runtime runtime = Runtime.getRuntime();
			Process proc = runtime.exec("mount");
			InputStream is = proc.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);

			String line;

			while ((line = br.readLine()) != null) {
				if (line.contains("secure")) {
					continue;
				}

				if (line.contains("asec")) {
					continue;
				}

				if (line.contains("fat") && line.contains("/mnt/")) {
					String columns[] = line.split(" ");

					if (columns != null && columns.length > 1) {
						if (sd_default.trim().equals(columns[1].trim())) {
							continue;
						}

						sdcard_path = columns[1];
					}
				} else if (line.contains("fuse") && line.contains("/mnt/")) {
					String columns[] = line.split(" ");

					if (columns != null && columns.length > 1) {
						if (sd_default.trim().equals(columns[1].trim())) {
							continue;
						}

						sdcard_path = columns[1];
					}
				}
			}

			is.close();
			isr.close();
			br.close();
			proc.destroy();// FIXME
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Log.d("text", sdcard_path);
		return sdcard_path;
	}

	/**
	 * 鑾峰彇澶栫疆SD鍗�(sdcrad1)璺�?
	 * 
	 * @return
	 */
	public static String getSDCard2Path_M2() {
		final String[] pathArray = new String[] { "/storage/sdcard1", "/storage/usbcard1/", //
				"/mnt/extSdCard/", "/mnt/external_sd/", "/mnt/sdcard-ext", "/mnt/sdcard1", "/mnt/sdcard2" };

		// String sdCard_2 = recursion_M1(pathArray, 0);

		String sdCard_2 = recursion_M2(pathArray);

		return sdCard_2;
	}

	public static String recursion_M1(String[] pathArray, int currentIndex) {

		if (pathArray == null || pathArray.length <= currentIndex) {
			return "";
		}

		String tempPath = pathArray[currentIndex];

		File fileTemp = new File(tempPath);

		if (fileTemp.exists()) {
			return tempPath;
		} else {
			return recursion_M1(pathArray, ++currentIndex);
		}
	}

	public static String recursion_M2(String[] pathArray) {

		String result = "";

		if (pathArray != null) {
			int size = pathArray.length;

			for (int i = 0; i < size; i++) {
				String tempPath = pathArray[i];

				File fileTemp = new File(tempPath);

				if (fileTemp.exists()) {
					return tempPath;
				}
			}
		}

		return result;
	}

	/**
	 * 鑾峰�? 鎸囧畾璺緞 鎵�鍦ㄧ┖闂寸殑 鍓╀綑鍙敤瀹归�? 瀛楄妭鏁�?, 鍗曚綅byte
	 * 
	 * @param filePath
	 * @return 瀹归噺�?�楄�? SDCard鍙敤绌洪棿, 鍐呴儴�?�樺偍鍙敤绌洪�?
	 */
	@SuppressWarnings("deprecation")
	public static long getFreeBytes(String filePath) {
		StatFs stat = new StatFs(filePath);

		// 鑾峰彇绌洪棽鐨勬暟鎹潡鐨勬暟閲�?
		long availableBlocks = (long) stat.getAvailableBlocks() - 4;

		// 鑾峰彇鍗曚釜鏁版嵁鍧楃殑澶у皬(byte)
		long blockSize = stat.getBlockSize();

		return blockSize * availableBlocks;
	}

	/**
	 * 鎶婂瓧鑺傛暟缁勪繚�?�樹负涓�涓枃浠�
	 *
	 * @param b
	 * @param outputFile
	 * @return
	 */
	public static File getFileFromBytes(byte[] b, String outputFile) {
		File ret = null;
		BufferedOutputStream stream = null;
		try {
			ret = new File(outputFile);
			if (!ret.exists()) {
				ret.mkdirs();
			}
			FileOutputStream fstream = new FileOutputStream(ret);
			stream = new BufferedOutputStream(fstream);
			stream.write(b);
		} catch (Exception e) {
			// log.error("helper:get file from byte process error!");
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) {
					// log.error("helper:get file from byte process error!");
					e.printStackTrace();
				}
			}
		}
		return ret;
	}
}
